package com.xiaojiezhu.test.mybatis;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.util.Properties;

/**
 * 作者 zxj<br>
 * 时间 2017/10/22 17:11
 * 可拦截的四大接口
 * Executor 拦截执行器的方法
 * ParameterHandler 拦截参数的处理
 * ResultSetHandler 拦截结果集的处理
 * StatementHandler 拦截Sql语法构建的处理
 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class}) })
public class MyPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();

        System.out.println(sql);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
/*        // 假如我们只要拦截Executor对象，那么我们应该这么做，减少不必要的代理
        public Object plugin(final Object target) {
            if (target instanceof Executor) {
                return Plugin.wrap(target, this);
            } else {
                return target;
            }
        }*/
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
